package com.lhsy.djcloud.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.controller.vo.AccountVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.Employee;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.AccountDto;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.EmployeeService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-09-24
 */
@RestController
@RequestMapping("/account")
@Api(value = "Server-API",tags = "账号管理")
public class AccountController extends BaseController{
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private EmployeeService employeeService;

    @ApiOperation(value = "分页加载账号列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ReturnT updatePwd(HttpServletRequest request, @RequestParam(required = false) String userName,
                             @RequestParam(defaultValue = "1")Integer pageNo,
                             @RequestParam(defaultValue = "10")Integer pageSize,
                             @RequestParam(required = false)Integer level){
        UserDto currUser = getCurrUser(request);
        if(!currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"权限不足");
        }
        List<AccountDto> accountDtos = Lists.newArrayList();
        PageHelper.startPage(pageNo,pageSize);
        accountDtos = userService.selectAccountList(userName,level,currUser.getTenantId());
        PageInfo<AccountDto> accountDtoPageInfo = new PageInfo<>(accountDtos);
        return ReturnT.SUCCESS(accountDtoPageInfo);
    }

    @ApiOperation(value = "查看")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public ReturnT noselfList(HttpServletRequest request,@PathVariable Integer id){
        UserDto currUser = getCurrUser(request);
        if (!currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"暂无权限");
        }
        User user = userService.getById(id);
        Department department = departmentService.getById(user.getDeptId());
        Department byId = departmentService.getById(department.getFid());
        if (Objects.nonNull(byId)){
            department.setFDeptName(byId.getDeptName());
        }
        user.setDepartment(department);
        user.setPassword(null);
        //查询党员人数
        //查询当前党下的所有党小组
        List<Integer> deptidsSearch = Lists.newArrayList();
        if (department.getLevel() == 1){
            //查询所有的党小组
            List<Department> departments = departmentService.getByLevel(currUser.getTenantId(), 3);
            deptidsSearch  = departments.stream().map(Department::getId).collect(Collectors.toList());
        }
        if (department.getLevel() == 2){
            List<Department> departments = departmentService.selectByPid(byId.getId());
            deptidsSearch  = departments.stream().map(Department::getId).collect(Collectors.toList());
        }
        if (department.getLevel() == 3){
            List<Department> departments = departmentService.selectByPid(byId.getId());
            deptidsSearch  = departments.stream().map(Department::getId).collect(Collectors.toList());
        }
        List<Employee> employees = employeeService.selectByDeptIds(deptidsSearch);
        user.setCount(employees.size());
        return ReturnT.SUCCESS(user);
    }

    @ApiOperation(value = "账户修改(只能修改用户名密码)")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ReturnT add(HttpServletRequest request,@RequestBody AccountVo accountVo){
        UserDto currUser = getCurrUser(request);
        if (!currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"暂无权限");
        }

        User user = userService.getById(accountVo.getUserId());
        if (user == null){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"用户不存在");
        }
        //查询用户名是否存在
        if (!user.getUsername().equals(accountVo.getUserName())){
            //验证管理员是否存在
            User oldUser = userService.selectByUserName(accountVo.getUserName());
            if (Objects.nonNull(oldUser)){
                return ReturnT.FAIL(ReturnT.FAIL_401,"当前用户名已经存在");
            }
        }
        //更新用户信息
        if (StrUtil.isNotBlank(accountVo.getNewPwd())){
            user.setPassword(SecureUtil.md5(accountVo.getNewPwd()));
        }
        if (StrUtil.isNotBlank(accountVo.getUserName())){
            user.setUsername(accountVo.getUserName());
        }
        userService.updateById(user);
        return ReturnT.SUCCESS;
    }
}

